import { useTitle } from 'ahooks'
import React, { useEffect, useRef, useState } from 'react'
import skf from './Components/skf.svg'
import fkf from './Components/fkf.svg'
import style from './Components/RecordSure.less'
import more from './Components/more.svg'
import more2 from './Components/more2.svg'
import map from './Components/path.svg'
import block from './Components/block.svg'
import dustbin from './Components/dustbin.svg'
import rules from './Components/rules.svg'
import goodsAdd from './Components/goodsAdd.svg'
import Microphone from './Components/Microphone.svg'
import { Button, Collapse, DatePicker, DatePickerRef, Dialog, Form, Input, Picker, TextArea, Toast, Space } from 'antd-mobile'
import { Panel } from 'antd-mobile/es/components/index-bar/panel'
import choose from './Components/choose.svg'
import { useForm } from 'rc-field-form'
import { DownOutline, AddCircleOutline } from 'antd-mobile-icons'
import dayjs from 'dayjs'
import { history, useLocation } from 'umi'
import { get } from 'lodash'
import { getCollectTicketTure } from '@/services/Title'

export default function RecordSure() {
  useTitle('录单开票');
  const content = "1111111111111111111111111111111111111111111111111111111111111"
  const [form] = Form.useForm()
  const Info: any = history.location?.state
  const [enterprise, setEnterprise] = useState<any>()

  //总价
  const totalRef = useRef(0)
  //title可见
  const [visually, setVisually] = useState<any>()
  //地区可见
  const [visible, setVisible] = useState(false)
  const [position, setPosition] = useState<any>("")
  const [carId, setCarId] = useState<any>("")
  const goodsList = useRef<number>(1)
  //车牌地区
  const columns = [[
    { label: '', value: '' },
    { label: '渝', value: '渝' }, { label: '滇', value: '滇' },
    { label: '黑', value: '黑' }, { label: '浙', value: '浙' },
    { label: '吉', value: '吉' }, { label: '赣', value: '赣' },
    { label: '辽', value: '辽' }, { label: '粤', value: '粤' },
    { label: '冀', value: '冀' }, { label: '闽', value: '闽' },
    { label: '甘', value: '甘' }, { label: '台', value: '台' },
    { label: '青', value: '青' }, { label: '琼', value: '琼' },
    { label: '陕', value: '陕' }, { label: '黔', value: '黔' },
    { label: '豫', value: '豫' }, { label: '皖', value: '皖' },
    { label: '鲁', value: '鲁' }, { label: '湘', value: '湘' },
    { label: '晋', value: '晋' }, { label: '川', value: '川' },
    { label: '鄂', value: '鄂' }, { label: '苏', value: '苏' },
  ], [
    { label: '', value: '' },
    { label: 'A', value: 'A' },
    { label: 'B', value: 'B' },
    { label: 'C', value: 'C' },
    { label: 'D', value: 'D' },
    { label: 'E', value: 'E' },
    { label: 'F', value: 'F' },
    { label: 'G', value: 'G' },
    { label: 'H', value: 'H' },
  ],]
  //提交
  const onFinish = async (data: any) => {

    console.log('onFinish', data);

    var total = totalRef.current

    //判断是否超额
    if (totalRef.current < 6000) {
      //交易规则框
      Dialog.show({
        content: <><div>您本次开票已超出免验额度，如果继续开票，需进一步校验交易信息。</div>
          <div style={{ display: "flex", justifyContent: "center" }}
            onClick={() => {
              Dialog.show({
                content: <span><span >基础免验额度：</span><br />
                  <span style={{ color: "rgba(166,166,166)" }}>每个自然人拥有连续12个月内<span style={{ color: "#21B47C" }}>6万元</span>的免验开票额度。超出后需完善交易信息再开票。（单笔部分超出的，整笔都需完善交易信息。）</span><br />

                  <br /><span >免验扣除规则：</span>
                  <span style={{ color: "rgba(166,166,166)" }}> 去税局开票即冻结整笔订单金额，<span style={{ color: "#21B47C" }}>半小时</span>未开票、取消、废除开票即解除冻结，申请开票成功即扣除。</span><br />

                  <br /><span >先票后款额度：</span>
                  <span style={{ color: "rgba(166,166,166)" }}> 每个自然人在完善交易时，拥有<span style={{ color: "#21B47C" }}>5张</span>先开具发票后补款（先票后款）订单机会。</span><br /><br />

                  <span style={{ color: "rgba(166,166,166)" }}>去税局开票即视为已使用一张先票后款机会，取消或补款通过审核增加一张。<span style={{ color: "#21B47C" }}>使用上限为五张。</span></span></span>,
                closeOnAction: true,
                closeOnMaskClick: true,
                title: '交易真实性校验说明',
                actions: [[
                  {

                    key: "cancel",
                    text: "取消",
                    style: React.CSSProperties = { color: 'black' }
                  },
                  {

                    key: "sure",
                    text: "继续",
                    style: React.CSSProperties = { color: 'rgba(33, 180, 124, 1)' }
                  },]
                ],
              })
            }}>
            <img src={rules} style={{ width: "50%" }} />
          </div></>,
        actions: [
          [
            {
              key: 'cancel',
              text: '取消',
            },
            {
              key: 'sure',
              text: '确认',
              style: React.CSSProperties = { color: 'rgb(33,180,124)' }
            },
          ],
        ],
        closeOnAction: true,
        closeOnMaskClick: true,
        onAction(action, index) {
          if (action.key == 'sure') {
            // 跳转
            const value = { ...data, total, path: '/Invoice/RecordSure' }
            history.push(
              '/Invoice/RefineOrder'
              , { state: value }
            )
          }
        }
      })
    }
  }
  const onValueChange = (data: any) => {
    console.log('地区', data);
    form.resetFields(['carArea'])
    const value = data[0] + data[1]
    form.setFieldValue('carArea', value)
    if (data[0] && data[1]) {
      setPosition(value)
    } else {
      setPosition("")
    }





  }

  const onChange = (data: any) => {
    console.log('onChange', data);
    setVisually(data)
  }
  //监听form.array
  const values = Form.useWatch('contacts', form);
  totalRef.current = 0;
  (values || [{}]).forEach((i, index) => {
    if (i?.unitPrice || i?.cargoNumber) {
      form.setFieldValue(['contacts', index, 'sum'], Number(((i?.unitPrice || 0) * (i?.cargoNumber || 0)).toFixed(2)))

    }
    if (i?.sum) {
      totalRef.current = Number(((i?.unitPrice || 0) * (i?.cargoNumber || 0)).toFixed(2)) + totalRef.current
    }
  })
  //获取用户信息
  const getUserData = async () => {
    // const res = await 
  }
  //获取企业信息
  const getEnterpriseData = async () => {
    const res = await getCollectTicketTure()
    console.log(res);
    setEnterprise(res)
  }
  useEffect(() => {
    getUserData()
    getEnterpriseData()
  }, [])
  return (
    <div className={style.styles}>
      <div className={style.style_div1}>
        <div style={{ display: "flex", alignItems: "center", height: "50px" }} >
          <img src={skf} style={{ width: "40px", height: "18px" }} alt="" />
          <div style={{ marginLeft: "10px" }}>
            <span className={style.div1_span}>用户名</span>
            <div>500***********7567</div>
          </div>
        </div>
        <div onClick={() => {
          history.push(
            '/Invoice/InvoiceTitle'
          )
        }
        } style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: "50px" }}>
          <div style={{ display: "flex", alignItems: "center", height: "50px" }}>
            <img style={{ width: "40px", height: "18px", marginRight: "10px" }} src={fkf} alt="" />
            <div className={style.div1_span}> 重庆中链融科技有限公司{enterprise?.enterprise} </div>
            <img style={{ width: "9px", height: "15px", marginLeft: "10px" }} src={more} alt="" />
          </div>

          <img style={{ width: '20px', height: "20px" }} src={more2} alt="" />
        </div>
      </div>
      <div className={style.div2}>
        <span style={{ width: "73.5px" }}>业务发生地</span>
        <div style={{ display: "flex", alignItems: "center", flex: 1, minWidth: 0, margin: "0 10px" }}>
          <img src={map} style={{ width: "12.4px", height: "15px" }} alt="" />
          <div className={style.ellipsis} >{content}</div>
        </div>
        <span style={{ color: "#21B47C", fontSize: "15px" }}>重新定位</span>
      </div>
      <Form
        form={form}
        layout='horizontal'
        onFinish={onFinish}
        initialValues={{
          contacts: Info?.state.contacts == null ? [{}] : Info.state.contacts,
        }}

        footer={
          <div className={style.footer}>
            <div style={{ marginTop: "4px" }}>
              <div style={{ color: "red", flex: 1, maxWidth: "50vw", overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis" }}>¥<span style={{ fontSize: "18px", color: "red", fontWeight: "bold" }}>{totalRef.current.toLocaleString()}</span></div>
              <div style={{ fontSize: "10px", color: "#999999", marginTop: "2px" }}>订单总金额</div>
            </div>
            <Button type='submit' color='success' style={{ width: "155px", height: "48px" }}> 提交 </Button>
          </div>
        }
      >
        <div className={style.div3}>
          <div style={{ width: "100%" }}>
            <div style={{ display: "flex", alignItems: "center" }}>
              <img style={{ width: "5px", height: "14px" }} src={block} alt="" />
              <div className={style.div3_1}>货劳明细</div>
            </div>
            <div>
              <Form.Array
                name='contacts'

                onAdd={operation => { goodsList.current <= 7 ? operation.add() : '' }}
                renderAdd={() => (
                  <span onClick={() => {
                    { goodsList.current == 8 ? Toast.show(`货物总数不能超过八`) : '' }
                  }}>
                    <AddCircleOutline /> 添加
                  </span>
                )}
              >
                {(fields, { remove }) =>
                  fields.map((items, index) => (
                    <>
                      <Collapse accordion defaultActiveKey={Info == null ? index + '' : ''} onChange={onChange}>
                        <Collapse.Panel key={index + ''} title={
                          <div >
                            <span>第{goodsList.current = index + 1}项</span>
                            {(form.getFieldValue(['contacts', index, 'cargoSorts']) == null ? true : visually == index ? true : false) ? '' : <span style={{ marginLeft: "10px", fontSize: "13px", color: "#999999" }}>{form.getFieldValue(['contacts', index, 'cargoSorts'])}</span>}
                            {(form.getFieldValue(['contacts', index, 'sum']) == null ? true : visually == index ? true : false) ? '' :
                              <div style={{ position: "relative", left: "0px", right: "0px", bottom: "0px", display: "flex", justifyContent: "space-around", fontSize: "13px" }}>
                                <div className={style.titleValues}>
                                  <div >
                                    <Form.Item
                                      name={[index, 'cargoNumber']}
                                      label={<span style={{ color: "#999999" }}>数量</span>}
                                    >
                                      <Input style={{ "--color": "#999999", "--font-size": "14px" }} readOnly />
                                    </Form.Item>
                                  </div>
                                  <div style={{ opacity: "0.3" }}>|</div>
                                  <div className={style.titleValues}>
                                    <Form.Item
                                      name={[index, 'sum']}
                                      label={<span style={{ color: "#999999" }}>金额</span>}
                                    >
                                      <Input style={{ "--color": "#999999", "--font-size": "14px" }} readOnly />
                                    </Form.Item>
                                  </div></div>
                              </div>}
                          </div>

                        }>
                          <Form.Item label='货物分类' name={[index, 'cargoSorts']} className={style.style_form2}
                            rules={[{
                              required: true,
                              message: '货物种类为必填项',
                            }]}
                            getValueFromEvent={e=>{
                              setVisually(index)
                              return e
                            }}
                            extra={
                              <img src={choose} style={{ width: "47px", height: "21px" }} />
                            }>
                            <Input
                              placeholder='请输入' clearable style={{ '--text-align': 'right', '--font-size': '15px' }} />
                          </Form.Item>
                          <Form.Item
                            rules={[{
                              pattern: /^.{0,20}$/,
                              message: '数据过长',
                            }]}
                            label='规格型号' name={[index, 'models']} className={style.style_form2} >
                            <Input
                              placeholder='请输入规格型号' clearable type='text' style={{ '--text-align': 'right', '--font-size': '15px' }} />
                          </Form.Item>
                          <Form.Item label='数量'
                            getValueFromEvent={e => {
                              setVisually(index)
                              return e
                            }}
                            rules={[{
                              required: true,
                              message: '数量为必填项',
                            }, {
                              pattern: /(^[1-9]\d{0,8}(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
                              message: "数值有误或过大",
                            }]}
                            className={style.style_form} name={[index, 'cargoNumber']} extra={'斤'}>
                            <Input
                              placeholder='请输入' clearable type='text' style={{ '--text-align': 'right', '--font-size': '15px' }} />
                          </Form.Item>
                          <Form.Item label='单价'
                            getValueFromEvent={e => {
                              setVisually(index)
                              return e
                            }}
                            rules={[{
                              required: true,
                              message: '单价为必填项',
                            }, {
                              pattern: /(^[1-9]\d{0,5}(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
                              message: "数值有误或过大",
                            }]}
                            className={style.style_form} name={[index, 'unitPrice']} extra={'斤/元'}
                          >
                            <Input
                              placeholder='请输入' clearable type='text' style={{ '--text-align': 'right', '--font-size': '15px' }} />
                          </Form.Item>
                          <Form.Item label={<span>金额<span style={{ 'fontSize': '12px' }}>(不含税)</span></span>} className='style_form' name={[index, 'sum']} extra={'元'}>
                            {/* {form.getFieldsFormatValue?.()} */}
                            {/* {values ? (values[index]?.unitPrice || 0) * (values[index]?.cargoNumber || 0) : 0} */}
                            <Input
                              placeholder='请输入' clearable type='text' style={{ '--text-align': 'right', '--font-size': '15px' }} readOnly />
                          </Form.Item>
                          <div className={style.div4_button}>
                            <Button onClick={() => { goodsList.current == 1 ? Toast.show(`至少填写一个货物`) : remove(index) }} style={{ width: '87px', color: 'rgba(51, 51, 51, 1)', height: '34.5px', lineHeight: '17px' }}>
                              <img style={{ width: '15px', marginRight: '5px' }} src={dustbin} />删除</Button>
                          </div>
                        </Collapse.Panel>
                      </Collapse>
                    </>
                  ))
                }
              </Form.Array>
            </div>
          </div>
        </div>
        <div className={style.div4}>
          <span style={{ fontSize: "15px", fontWeight: "bold" }}>货运车辆信息</span>
          <div >
            <div className={style.list1}>
              <div style={{ marginRight: "29px", whiteSpace: "nowrap" }}>车牌号</div>
              <Form.Item name='carArea'
                className={style.carArea}
                onClick={() => setVisible(true)}
                initialValue={Info?.state?.carArea != null ? Info?.state.carArea : null}
                rules={[{
                  required: position == "" ? carId == "" ? false : true : carId != "" ? false : true,
                  message: '请填写完整',
                },
                // {validator: () => {

                // }},
                {
                  pattern: /^.{2,100}$/,
                  message: '请选择完整',
                }
                ]}
              >

                <Input placeholder='地区' />
              </Form.Item>
              <Form.Item
                name='carID'
                getValueFromEvent={e => {
                  setCarId(e)
                  return e
                }}
                rules={[{
                  required: position == "" ? carId == "" ? false : true : carId != "" ? false : true,
                  message: '请填写完整',
                }]}
                className={style.carNumber}
                initialValue={Info?.state?.carID != null ? Info?.state.carID : null}>
                <Input placeholder='请输入' />
              </Form.Item>
            </div>
            <div className={style.timeInfo}>
              <span style={{ marginRight: "12px", whiteSpace: "nowrap" }}>起运时间</span>
              <Form.Item
                name='startTime'
                trigger='onConfirm'
                className={style.timePick}
                initialValue={Info?.state?.startTime ?? null}
                onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
                  datePickerRef.current?.open()
                }}
              >
                <DatePicker
                  precision='minute'
                >
                  {value =>
                    value ? dayjs(value)?.format('YYYY-MM-DD') : <span style={{ 'fontSize': '15px', color: 'rgba(153, 153, 153, 1)' }}>请选择日期</span>
                  }
                </DatePicker>

              </Form.Item>

            </div>
          </div>
        </div>

        <div className={style.div5}>
          <span style={{ fontSize: "15px", fontWeight: "bold" }}>发票票面备注</span>
          <div>
            <Form.Item
              name='InvoiceNotes'
              rules={[{
                pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
                message: "禁止输入特殊字符",
              }]}
              initialValue={Info?.state.InvoiceNotes != null ? Info?.state.InvoiceNotes : ''}>
              <TextArea
                className={style.div5_text}
                showCount
                placeholder={'请填写，非必填（80字符以内）'}
                maxLength={80}
              />
            </Form.Item>
          </div>
        </div>
      </Form>
      <Picker
        columns={columns}
        visible={visible}
        onClose={() => {
          setVisible(false)
        }}
        onConfirm={onValueChange}
      />
      <div className={style.div6}></div>
    </div>
  )
}
